/*
	工程离职交接申请
*/

public without sharing class EngineerHandoverController {
    
    public String msg {get; private set;}
   	public Boolean isErr {get; private set;}
   	public Boolean isSuccess {get;private set ;}

   	public String backId {get;private set;}

   	public String dataJson {get;private set;}
   	public String saveJson {get; set;}
    public String errorJson {get;private set;}

    public Boolean isComfirm {get; private set;}


   	private EngineerHandover__c eh;
    public EngineerHandoverController() {
        eh = new EngineerHandover__c();
        backId = System.currentPageReference().getParameters().get('id');
        errorJson='[]';

    }

    public void init(){
        // User u ;
        // u.EmployeeNumber

    	try {

    	    eh = [select Id ,OwnerId,Status__c  from EngineerHandover__c where Id=:backId];
            
            System.debug(eh);
            isComfirm = false;
            isComfirm = eh.Status__c == '审批中';
            System.debug(eh.Status__c == '审批中' );
            System.debug(isComfirm);

            if(eh.Status__c == '已批准' )throw new DmlException('申请单'+eh.Status__c + '不能修改!');
    		 List<DetailBean> tmp = getDetail();

            if(isComfirm && tmp.isEmpty())throw new DmlException('没有需要确认接收的配件!');
    		if(!isComfirm && tmp.isEmpty())throw new DmlException('没有需要交接的借出配件!');
    	
    		dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');
    	}
    	catch (Exception e) {
    	    isErr = true;
    		ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
    	}
    	
    	
    }

    public void save(){
    	msg = '';
    	try {

            Map<String,Object> saveMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
            Boolean isCommit = Boolean.valueOf(saveMap.get('commit')) ;
    	    List<Object> saveList = (List<Object>) saveMap.get('data');

    	    List<HandoverDetails__c> details = new List<HandoverDetails__c>();
    	    Set<String> esets = new Set<String>();
    	    for (Object o  :saveList ) {
    	    	Map<String,Object> mo = (Map<String,Object>)o;
    	    	HandoverDetails__c p = new HandoverDetails__c();
    	    	p.Id = DataUtil.getStringValue(mo.get('dId'));
                p.Quantity__c = DataUtil.getDecimalValue(mo.get('num'));
                p.Product__c = DataUtil.getStringValue(mo.get('productId'));
    	    	p.PartsLendingDetails__c = DataUtil.getStringValue(mo.get('detailId'));
    	    	if(p.Id == null )p.MasterTable__c  = backId;
    	    	if(p.Id != null)esets.add(p.Id);
                p.ReceivingPerson__c = DataUtil.getStringValue(mo.get('userId'));
                
    	    	details.add( isComfirm ? new HandoverDetails__c(Id=p.Id , ConfirmHandover__c = true ) :p );
    	    }
    	    SavePoint sp = Database.setSavepoint();
    	    try {
    	        
                 if(isCommit){
                    eh.Status__c = '审批中';
                    update eh;
                }
    	        if(!details.isEmpty())upsert details;
    	        isSuccess = true;
    	        msg = '保存成功!';

    	    }
    	    catch (Exception e) {
    	    	Database.rollback(sp);
    	   		msg = '保存失败:'+e.getMessage() +e.getStackTraceString(); 
    	    }
    	    
    	}catch (Exception e) {
    	   msg = '保存失败:'+e.getMessage() +e.getStackTraceString(); 
    	}
    	System.debug('EngineerHandoverController==>'+ msg);
    }

    public List<DetailBean> getSearch(){
    	List<DetailBean> tmp =new List<DetailBean>();
        Set<String> psets = new Set<String>();
        List<PartsLendingDetails__c> errorList = new List<PartsLendingDetails__c>();
    	for (PartsLendingDetails__c p :[ select  Id,Name, Product__r.Name,Product__c,LendingMargin__c , 
            No__c, A_InvoiceNo__c,A_ReturnNo__c, A_WarrantyNo__c  , B_No__c, B_InvoiceNo__c, B_ReturnNo__c,B_WarrantyNo__c,
            PartsLendingApplication__r.Name  ,PartsLendingApplication__c 
          from PartsLendingDetails__c where LendingMargin__c  > 0  
    		and PartsLendingApplication__r.OwnerId =:eh.OwnerId and PartsLendingApplication__r.IsSycToNc__c =true   ] ) {
           
            tmp.add(new DetailBean(p));
            Decimal acNo = p.No__c - p.A_InvoiceNo__c - p.A_ReturnNo__c - p.A_WarrantyNo__c ;
            Decimal bNo = p.B_No__c - p.B_InvoiceNo__c - p.B_ReturnNo__c - p.B_WarrantyNo__c ;
           if(  acNo!=  bNo)errorList.add(p);


    	}
        errorJson = EncodingUtil.urlEncode(JSON.serialize(errorList), 'UTF-8');

    	return tmp;
    }

    public List<DetailBean> getDetail(){
    	
    	List<DetailBean> tmp =new List<DetailBean>();
        String sql = 'select Id,ReceivingPerson__r.Name,ReceivingPerson__c ,PartsLendingDetails__c , PartsLendingDetails__r.Name ,'+
        'Product__r.Name,Product__c,Quantity__c from HandoverDetails__c where MasterTable__c =\''+backId+'\' ';
        
        if(isComfirm)sql += ' and  ReceivingPerson__c = \''+UserInfo.getUserId()+'\' ';

        System.debug(isComfirm + ' '+sql);
    	for (HandoverDetails__c p :Database.query(sql) ) {
    		tmp.add(new DetailBean(p));
    	}

    	if(!isComfirm && tmp.isEmpty())tmp.addAll(getSearch());
    	return tmp;

    }

    public class DetailBean{
    	public String detailId ;
    	public String detailName;
    	public String dId;
        public String userName;
        public String userId;
        public Decimal num;
        public String productId;
        public String productName;


    	public DetailBean(PartsLendingDetails__c arg ){
    		detailId = arg.Id;
    		detailName = arg.Name ;

            productName = arg.Product__r.Name;
            productId = arg.Product__c;

            num = arg.LendingMargin__c;

    	}

    	public DetailBean(HandoverDetails__c arg ){
    		detailId = arg.PartsLendingDetails__c ;
    		detailName =  arg.PartsLendingDetails__r.Name;
    		dId = arg.Id ;
            userId = arg.ReceivingPerson__c;
            userName = arg.ReceivingPerson__r.Name;
            productId = arg.Product__c;
            productName = arg.Product__r.Name ;
            num = arg.Quantity__c;

    	}	
    }
}